package com.yjb.demo.websocket.client.application;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;

/**
 * @author yjb
 * @description
 * @create 2024/9/24 9:19
 */
@Slf4j
@ClientEndpoint
public class WebSocketClientDemo {

    /**
     * ws 路径
     */
    private final String uri;

    public WebSocketClientDemo(String uri){
        this.uri = uri;
    }

    @OnOpen
    public void onOpen(Session session) {
        //连接建立
        log.info("client open");
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        //连接关闭
        log.info("client close");
        reconnect();
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        //接收文本消息
        log.info(message);
        session.getBasicRemote().sendText("world");
    }

    @OnMessage
    public void onMessage(Session session, PongMessage message) {
        //接收pong消息
        log.info(message.toString());
    }

    @OnMessage
    public void onMessage(Session session, ByteBuffer message) {
        //接收二进制消息
        log.info(message.toString());
    }

    @OnError
    public void onError(Session session, Throwable e) {
        //异常处理
        e.printStackTrace();
    }

    /**
     * 重连
     */
    private void reconnect() {
        while (true){
            try {
                // 等待5秒后尝试重连
                Thread.sleep(5000);
                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                URI endpointURI = new URI(uri);
                Session session = container.connectToServer(this, endpointURI);
                if (session.isOpen()){
                    return;
                }
            }catch (Exception e) {
                log.error("websocket 客户端连接失败，uri = {}",uri, e);
            }
        }
    }
}
